<template>
  <div class="table-demo">
    <h2>Basic Table Example</h2>
    
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true">
        <el-form-item label="Name">
          <el-input v-model="searchParams.name" placeholder="Search by name" @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="Status">
          <el-select v-model="searchParams.status" placeholder="Select status" clearable>
            <el-option label="Enabled" :value="1" />
            <el-option label="Disabled" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">Search</el-button>
          <el-button @click="handleReset">Reset</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <UXTable
     
      @register="registerTable"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
    >
      <!-- Custom action column -->
      <template #action>
        <el-table-column fixed="right" label="Actions" width="200" align="center">
          <template #default="scope">
            <TableAction
              :actions="[
                {
                  label: 'View',
                  onClick: () => handleView(scope.row),
                  type: 'primary',
                  size: 'small'
                },
                {
                  label: 'Edit',
                  onClick: () => handleEdit(scope.row),
                  type: 'warning',
                  size: 'small'
                },
                {
                  label: 'Delete',
                  onClick: () => handleDelete(scope.row),
                  type: 'danger',
                  size: 'small',
                  popConfirm: {
                    title: 'Are you sure you want to delete this record?',
                    confirm: () => confirmDelete(scope.row)
                  }
                }
              ]"
            />
          </template>
        </el-table-column>
      </template>
    </UXTable>

    <div v-if="selectedRows.length > 0" class="result-panel">
      <h3>Selected Rows:</h3>
      <pre>{{ JSON.stringify(selectedRows, null, 2) }}</pre>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, h } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  UXTable, 
  TableAction, 
  useUXTable, 
  useUXTableWithApi,
  type TableColumn,
  type ApiFunction,
  type FetchParams,
  type FetchResult
} from '@axewo/ux-element'

// Selected rows
const selectedRows = ref<any[]>([])

// Search params
const searchParams = reactive({
  name: '',
  status: undefined as number | undefined,
})

// Table column definitions
const columns: TableColumn[] = [
  {
    prop: 'name',
    label: 'Name',
    width: 120
  },
  {
    prop: 'age',
    label: 'Age',
    width: 80
  },
  {
    prop: 'gender',
    label: 'Gender',
    width: 80
  },
  {
    prop: 'phone',
    label: 'Phone',
    width: 130
  },
  {
    prop: 'email',
    label: 'Email',
    width: 200,
    ellipsis: true
  },
  {
    prop: 'address',
    label: 'Address',
    minWidth: 180,
    ellipsis: true
  },
  {
    prop: 'status',
    label: 'Status',
    width: 100,
    customRender: ({ text }) => {
      if (text === 1) {
        return h('el-tag', { type: 'success' }, () => 'Enabled');
      } else {
        return h('el-tag', { type: 'danger' }, () => 'Disabled');
      }
    }
  },
  {
    prop: 'createTime',
    label: 'Created Time',
    width: 180,
    sorter: true
  }
]

// Mock API function
const fetchUserList: ApiFunction = async (params: FetchParams): Promise<FetchResult> => {
  const { page, pageSize, name, status } = params
  console.log('Fetching data with params:', params)
  
  // Simulate API request delay
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // Base user data
  const baseUsers = [
    {
      id: 1,
      name: 'John Doe',
      age: 25,
      gender: 'Male',
      phone: '13812345678',
      email: 'john.doe@example.com',
      address: 'New York, USA',
      status: 1,
      createTime: '2023-01-15 09:30:12'
    },
    {
      id: 2,
      name: 'Jane Smith',
      age: 32,
      gender: 'Female',
      phone: '13987654321',
      email: 'jane.smith@example.com',
      address: 'Los Angeles, USA',
      status: 0,
      createTime: '2023-02-20 15:45:30'
    },
    {
      id: 3,
      name: 'Bob Johnson',
      age: 28,
      gender: 'Male',
      phone: '13567891234',
      email: 'bob.johnson@example.com',
      address: 'Chicago, USA',
      status: 1,
      createTime: '2023-03-10 11:20:05'
    },
    {
      id: 4,
      name: 'Alice Brown',
      age: 35,
      gender: 'Female',
      phone: '13654789012',
      email: 'alice.brown@example.com',
      address: 'San Francisco, USA',
      status: 1,
      createTime: '2023-04-05 16:10:45'
    },
    {
      id: 5,
      name: 'Charlie Wilson',
      age: 26,
      gender: 'Male',
      phone: '13912345678',
      email: 'charlie.wilson@example.com',
      address: 'Boston, USA',
      status: 0,
      createTime: '2023-05-18 10:35:22'
    }
  ]
  
  // Create more data for demonstration
  const mockData = Array.from({ length: 100 }).map((_, index) => {
    const id = index + 1
    const baseUser = baseUsers[index % baseUsers.length]
    return {
      ...baseUser,
      id,
      name: name ? `${name}-${id}` : `User ${id}`,
      email: `user${id}@example.com`,
      status: status !== undefined ? status : baseUser.status,
    }
  })
  
  // Filter data based on search params
  let filteredData = [...mockData]
  
  if (name) {
    filteredData = filteredData.filter(item => 
      item.name.toLowerCase().includes(name.toLowerCase())
    )
  }
  
  if (status !== undefined) {
    filteredData = filteredData.filter(item => item.status === status)
  }
  
  // Calculate pagination
  const total = filteredData.length
  const startIndex = (page - 1) * pageSize
  const endIndex = startIndex + pageSize
  const paginatedData = filteredData.slice(startIndex, endIndex)
  
  // Return data in expected format
  return {
    items: paginatedData,
    total
  }
}

// Use table API hook
const apiState = useUXTableWithApi({
  title: 'User Management',
  api: fetchUserList,
  immediate: true,
  searchInfo: searchParams,
  fetchParams: {
    page: 1,
    pageSize: 10
  },
  pagination: {
    current: 1,
    pageSize: 10,
    pageSizes: [10, 20, 50, 100],
  }
})

// Register the table
const [registerTable] = useUXTable({
  columns

})

// Search function
const handleSearch = () => {
  apiState.reload(true)
}

// Reset search form
const handleReset = () => {
  searchParams.name = ''
  searchParams.status = undefined
  apiState.reload(true)
}

// Row click handler
const handleRowClick = (row: any) => {
  console.log('Row clicked:', row)
}

// Selection change handler
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// View handler
const handleView = (row: any) => {
  ElMessage.info(`View user: ${row.name}`)
  console.log('View details:', row)
}

// Edit handler
const handleEdit = (row: any) => {
  ElMessage.success(`Edit user: ${row.name}`)
  console.log('Edit:', row)
}

// Delete handler
const handleDelete = (row: any) => {
  console.log('Preparing to delete:', row)
}

// Confirm delete handler
const confirmDelete = (row: any) => {
  ElMessage.success(`User deleted: ${row.name}`)
  console.log('Confirmed delete:', row)
  
  // Remove from data source
  apiState.deleteTableDataRecord(row.id)
}
</script>

<style scoped>
.table-demo {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.result-panel {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

h2 {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

h3 {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  color: #606266;
}
</style> 